<template>
    <view style="display: flex; flex-direction: column; height: 100vh">
		<xmInfo
		    :projectno="itemContent.projectno"
		    :projectname="itemContent.projectname"
		  ></xmInfo>
		  <view style="flex: 1;  overflow: scroll">
		<scroll-view class="scroll-list" scroll-y="true" @scrolltolower="loadMore" :refresher-enabled="true"
			:refresher-triggered="triggered" @refresherrefresh="refresherrefresh">
        <!-- <view class="cu-card"> -->
            <view v-for="(item,index) in list" :key="item.id" style="width: 100%; display: flex;align-items: center;justify-content: space-between; margin-top: 10px;background-color: #fff;padding: 10px;">
				<view style="display: flex;flex: 1;">
					<u-icon :name="fileUrl(item.filetype)" :size="80"></u-icon>
					<view  style="margin: 0 10px;width: 470rpx;overflow: hidden;">
						<view  class="text-lg"style="
												width: 100%;
										display: -webkit-box;
										-webkit-box-orient: vertical; 
										-webkit-line-clamp: 1; 
										overflow: hidden; 
										text-overflow: ellipsis;"> 
						{{item.attachmentname}}
						</view>
						<view style="color: #aaa;margin-top: 5px;">
							<view style="display: flex;justify-content: space-between;">
							 <text>录入：{{item.createDate.slice(0, 10)}}  {{item.uploadorname}}</text>	
							<!-- <text style="color: #aaa;margin-left:10px;"> {{item.fileUpload.fileEntity.fileSizeFormat}}</text> -->
							</view>
							<view >类型：{{item.fileuploadurlname || ''}}</view>
						</view>
					</view>
				</view>
				
				<view @click="xiazai(item.id)" style="width: 50px;color: #3E97B0;height: 60px;line-height: 60px;" v-if="flag">
					<view class="">
						下载
					</view>
				</view>
            </view>
        <!-- </view> -->
		<view v-if="list.length" class="loadmore">
			<u-loadmore :status="loadStatus"></u-loadmore>
		</view>
		<u-empty v-if="!list.length"></u-empty>
		</scroll-view>
        
		<view style="height: 80px"></view>
		<view class="btn-group cu-bar foot" style="height: 80px">
		    <button class="cu-btn  shadow-blur" @click="search">
		        <text class="cuIcon-search" style="margin-right: 10px;"> </text> 搜索
		    </button>
		</view>
		</view>
		<customDialog
		  :modalName="modalName"
		  @getModalName="getModalName"
		  :dictList="dictList"
		></customDialog>
    </view>
</template>
<script>
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
import customDialog from "./dialog.vue";
import {hasPermission} from '@/common/fire.js'
  export default{
  components: {xmInfo,customDialog },
    data(){
        return{
			triggered: false,
			loadStatus: 'loadmore',
			query: {
				pageNo: 1,
				pageSize: 20,
			},
			itemContent:{},
            list:[],
			flag:hasPermission('app:attachment:pmAttachment:down'),
			modalName: null,
			dictList: [],
        }
    },
	onShow() {
		this.query.pageNo = 1;
		this.loadList();
	},
	onLoad(e) {
	  this.getDictList();  
	  if (typeof e.item !== "undefined") {
	    try {
	      this.itemContent = JSON.parse(e.item);
		 this.query.projectno = this.itemContent.projectno
	      console.log(this.itemContent);
	    } catch (error) {
	      console.error("Failed to parse item:", error);
	    }
	  } else {
	    console.warn("Item is undefined.");
	  }
	},
	
    methods:{
		getDictList() {
		  this.$u.api.dictListData({ dictType: "zf_bz_file_type" }).then((res) => {
		    this.dictList = res;
		  });
		},
		
		xiazai(id){
			this.$u.api.zfgs.pmAttachmentCheck({id,type:'1'}).then(res => {
				console.log(res);
				if(res.result == '200'){
					let url = this.vuex_config.baseUrl + '/proj/attachment/pmAttachment/download?id=' + id+'&type=1'
					this.downloadAndOpenFile(url,id)
				}else if(res.result == '203'){
					const hostUrl = this.extractUrl(this.vuex_config.baseUrl);
					const dataurl = hostUrl + res.data;
				   	uni.setClipboardData({
						data: dataurl,
						success: ()=> {}
					});
					uni.showModal({
						title: '提示',
						content: '(大文件)链接已复制，请前往浏览器下载',
						showCancel: false,
						success: function(res) {}
					});
					
					// window.location.href = res.data
				}else{
					uni.showModal({
						title: '提示',
						content: res.message,
						showCancel: false,
						success: function(res) {}
					});
				}
			})
		},
		// 预览图片
		doPreviewImage(url) {
		  // const images = this.lists.map((item) => item.url || item.path);
		  uni.previewImage({
		    urls: [url],
		    current: url,
		    success: () => {
		      // this.$emit("on-preview", url, this.lists, this.index);
		    },
		    fail: () => {
		      uni.showToast({
		        title: "预览图片失败",
		        icon: "none",
		      });
		    },
		  });
		},
		async downloadAndOpenFile(serverUrl,id) {
		  const hostUrl = this.extractUrl(this.vuex_config.baseUrl);
		  let that = this
		  
		  uni.downloadFile({
		    url: serverUrl,
		    success: function (res) {
		      var filePath = hostUrl +res.tempFilePath;
		      console.log(filePath, res);
			  var index = res.tempFilePath.lastIndexOf(".");
			  var str = res.tempFilePath.substring(index + 1, res.tempFilePath.length);
			  let url = that.vuex_config.baseUrl + '/proj/attachment/pmAttachment/download?id=' + id+'&type=1'
			  if('.gif.bmp.jpeg.jpg.ico.png.tif.tiff'.includes(str) && str){
			  	that.doPreviewImage(res.tempFilePath)
			  }else{
			  	wx.openDocument({
					filePath: res.tempFilePath,
					showMenu: true,
					success: function (res) {
					  console.log("打开文档成功");
					},
					fail: function (err) {
						// 判断如果是ios 
						if (uni.getSystemInfoSync().platform == "ios") {
							uni.setClipboardData({
								data: url,
								success: ()=> {}
							});
							uni.showModal({
								title: '提示',
								content: '文件链接已复制，请前往浏览器下载',
								// showCancel: false,
								success: function(res) {}
							});
						} else {
								that.$u.toast("该文件无法在微信中打开！");
						}

						
					},
				 });
			  }
			  
		      
		    },
		    fail: function (err) {
		      console.log(err);
		    },
		  });
		},
		extractUrl(url) {
			const regex = /^http\:\/\/[^\/]+\//;
			const match = url.match(regex);
			return match ? match[0] : null;
		},
		click(item){
			let url = ''
			if(item.fileUpload.fileUrl.startsWith('http')){
				url = item.fileUpload.fileUrl
			}else{
				url = this.vuex_config.baseUrl + item.fileUpload.fileUrl
			}
			
			if('.gif.bmp.jpeg.jpg.ico.png.tif.tiff'.includes(item.fileUpload.fileEntity.fileExtension)){
				
				this.doPreviewImage(url)
			}else{
				this.downloadAndOpenFile(url)
			}
		},
		fileUrl(e){
			let src = e.toLowerCase()
			if('.gif.bmp.jpeg.jpg.ico.png.tif.tiff.image'.includes(src)){
				return '/static/image/file/png.png'
			}else if('.flv.swf.mkv.webm.mid.mov.mp3.mp4.m4v.mpc.mpeg.mpg.swf.wav.wma.wmv.avi.rm.rmi.rmvb.aiff.asf.ogg.ogv'.includes(src)){
				return '/static/image/file/mp4.png'
			}else if('.doc.docx'.includes(src)){
				return '/static/image/file/doc.png'
			}else if('.xls.xlsx.csv.excel'.includes(src)){
				return '/static/image/file/excel.png'
			}else if('.ppt.pptx'.includes(src)){
				return '/static/image/file/ppt.png'
			}else if('.pdf'.includes(src)){
				return '/static/image/file/pdf.png'
			}else if('.txt.xml.md'.includes(src)){
				return '/static/image/file/txt.png'
			}else if('.rar.zip.7z.tar.tgz.jar.gz.gzip.bz2.compression'.includes(src)){
				return '/static/image/file/rar.png'
			}else if('.dwg.cad'.includes(src)){
				return '/static/image/file/dwg.png'
			}else{
				return '/static/image/file/file.png'
			}
		},
		async refresherrefresh() {
			this.triggered = true
			this.query.pageNo = 1;
			await this.loadList()
			this.triggered = false
		},
		loadList(type) {
			this.$u.api.zfgs.pmAttachmentListDataApp(this.query).then(res => {
				if (res.list.length < 20 || res.list.length == 0) {
					this.loadStatus = "nomore";
				}
				var list = res.list;
				if (type == "add") {
					for (var i = 0; i < list.length; i++) {
						this.list.push(list[i])
					}
				} else {
					this.list = list;
				}
			})
		
		},
		loadMore() {
			this.loadStatus = "loading";
			setTimeout(() => {
				this.query.pageNo += 1;
				this.loadList("add");
			}, 100);
		},
		search() {
		  this.modalName = "DrawerModalR";
		},
		getModalName(item) {
		  console.log(item, "getModalName===");
		  const { modalName, query } = item;
		  this.modalName = modalName;
		  this.query = query;
		  this.query.pageNo = 1;
		  this.query.pageSize = 20;
		  this.query.projectno = this.itemContent.projectno
		  // if(this.query.projStatus == 0){
		  //   this.current = 0
		  // }else if(this.query.projStatus == 1 || this.query.projStatus == 3 || this.query.projStatus == 4|| this.query.projStatus == 5 || this.query.projStatus == 6 || this.query.projStatus == 7 ){
		  //   this.current = 4
		  // }
		  // console.log(this.query.projStatus ,'this.query.projStatus',this.current)
		  this.loadList();
		},

    }
  }

</script>
<style lang="scss" scoped>
	/deep/ .u-progress.data-v-0d33af60 {
		display: none;
	}
	/deep/.u-input__input.data-v-460c1d26 {
	    text-align: right;
	}
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot{
    background: #fff;
}
.cu-item{
  flex-wrap: wrap;
  padding: 15px !important;
}
.title{
    flex-shrink: 0;
}
.grid-square{
    margin-bottom: 0 !important;
}
::v-deep .u-input__input{
	text-align: right;
}
</style>